import { Global } from "@/Global";
export class WebSocketConnector {
    url: string;
    onMessage: (message: string) => void = <any>null;

    private _websocket: WebSocket = <any>undefined;
    private _disposed = false;


    constructor(url: string) {
        this.url = Global.ServerUrl.replace("http", "ws") + url;
    }

    connect = () => {
        console.info(this.url);
        this._websocket = new WebSocket(this.url);
        this._websocket.onmessage = (e: any) => {

            if (this.onMessage) {
                this.onMessage(e.data);
            }

        }

        this._websocket.onerror = () => {
            console.error(this.url + " onerror");
            this._websocket = <any>null;
            if (!this._disposed) {
                this.connect();
            }
        }

        this._websocket.onclose = () => {
            console.warn(this.url + " onclose");
            this._websocket = <any>null;
            if (!this._disposed) {
                this.connect();
            }
        }
    }

    close = () => {
        this._disposed = true;
        this._websocket?.close();
    }

    send = (msg: string) => {
        this._websocket?.send(msg);
    }

    private _autosendInternal = (msg: string, internal: number) => {
        if(this._disposed)
            return;
        
        try {
            this._websocket?.send(msg);
        } catch (error) {

        }

        window.setTimeout(() => {
            this._autosendInternal(msg, internal);
        }, internal);
    }

    autoSend = (msg: string) => {
        window.setTimeout(() => {
            this._autosendInternal(msg, 3000);
        }, 3000);
    }
}